/**
 * Created by Foreveross on 2017/2/28.
 */
import Redis from 'ioredis';
import redisConfig from '../config/redisConfig';
import middlewareStatus from '../services/middlewareStatus';

class RedisUtil extends Redis {
    constructor(options){
        super(options);
    }

    decr (key) {
        return new Promise ( (resolve, reject) => {
            super.decr(key , (error , result) => {
                !!error ? reject(error) : resolve(result);
            })
        });
    }

    get (key) {
        return new Promise ( (resolve, reject) => {
            super.get(key, (error, result) => {
                !!error ? reject(error) : resolve(result);
            })
        });
    }

    set (key, value) {
        return new Promise( (resolve, reject) => {
           super.set(key, value, (error, result) => {
               !!error ? reject(`redis set error: ${error}`) : resolve(result);
           });
        });
    }

    // 插入对象 hash
    hmset (key, jsonValue) {
        return new Promise( (resolve, reject) => {
           super.hmset(key, jsonValue, (error, result) => {
               !!error ? reject(`redis hmset error: ${error}`) : resolve(result);
           });
        });
    }

    publish (key, value) {
        return new Promise( (resolve, reject) => {
            super.publish(key, value, (error, result) => {
                !!error ? reject(`redis publish error: ${error}`) : resolve(result);
            });
        });
    }

}

const redisUtil = new RedisUtil (redisConfig);

redisUtil.on('ready' , () => {
    middlewareStatus.setRedisStatus(true);
});

redisUtil.on('close', () => {
    middlewareStatus.setRedisStatus(false);
});

redisUtil.on('error', (err) => {
    throw new Error(err)
});

export default redisUtil ;



